package com.wyl.rbac.service;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.wyl.rbac.model.Authority;
import com.wyl.rbac.model.User;
import com.wyl.rbac.repository.AuthoritiesRepository;
import com.wyl.rbac.repository.UserRepository;


public class UsersService implements UserDetailsService {
	
	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private AuthoritiesRepository authoritiesRepository;
	
/*	@PostConstruct	
	protected void initialize() {
		//accountRepository.save(new Account("user", "demo", "ROLE_USER"));
		if(userRepository.findByUsername("wyl@wyl.com")==null){
			User user = new User("wyl","wyl@wyl.com", "123456", "wyl");
			user.setUiPassword("123456");
			Authority authority = authoritiesRepository.findOne(1L);
			user.addAuthority(authority);
			userRepository.save(user);
		}
		
		if(userRepository.findByUsername("xyg@wyl.com")==null){
			User user = new User("xyg","xyg@wyl.com", "123456", "xyg");
			user.setUiPassword("123456");
			Authority authority = authoritiesRepository.findOne(1L);
			user.addAuthority(authority);
			userRepository.save(user);
		}
	}*/
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userRepository.findByUsername(username);
		if(user == null) {
			throw new UsernameNotFoundException("user not found");
		}
		
		return user;		
	}
	
	public void signin(User user) {
		SecurityContextHolder.getContext().setAuthentication(authenticate(user));
	}
	
	private Authentication authenticate(User user) {
		return new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(), user.getAuthorities());
	}
	


}
